package cn.itsource.system.interceptor;

import cn.hutool.core.util.StrUtil;
import cn.itsource.system.domain.Payload;
import cn.itsource.system.domain.Permission;
import cn.itsource.system.mapper.PermissionMapper;
import cn.itsource.system.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Component
public class PermissionInterceptor implements HandlerInterceptor {

    @Autowired
    private PermissionMapper permissionMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        response.setContentType("text/json;charset=utf-8");
        String status = request.getHeader("status");
        //如果status不为空，就证明是门户网站发的请求，那么直接放行
        if(StrUtil.isNotBlank(status)){
            return true;
        }

        //拿到当前url
        String uri = request.getRequestURI();
        //请求方法
        String method = request.getMethod();
        if(method.equals(RequestMethod.GET.toString()) || method.equals(RequestMethod.DELETE.toString())){
            //获取最后索引
            int index =  uri.lastIndexOf("/");
            //得到要滴换的值
            String substringed = uri.substring(index + 1);
            //获取uri
            uri = uri.replace(substringed, "{id}");
        }
        //把uri和methodType去数据库中进行查询
        Permission permission = permissionMapper.selectByMethodTypeAndUri(method, uri);
        //如果permission为空，就证明是公共资源，公共资源应该直接放行
        if (permission == null) {
            return true;
        }
        //获取token
        String token = request.getHeader("token");
        //不为空，就要查看一下，当前是否拥有指定的资源权限
        Payload payload = JwtUtil.parseJwtToken(token);
        //获取当前用户拥有的权限列表
        List<Permission> ownPermissions = payload.getPermissions();

        for (Permission ownPermission : ownPermissions) {
            //如果当前用户拥有此资源，就直接放行
            if(ownPermission.getUrl().equals(uri) && ownPermission.getMethodType().equals(method)){
                return true;
            }
        }
        response.getWriter().write("{\"success\":false,\"code\":403,\"message\":\"权限不足,请充值会员\"}");
        //否则就不放行
        return false;

    }
}
